package com.qf.shop.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.qf.shop.entity.User;
import com.qf.shop.service.IUserService;
import com.qf.shop.vo.ExcelUser;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ Author     ：lzq.
 * @ Date       ：Created in 9:23 2020/10/23
 */

    public class ExcelUserListener extends AnalysisEventListener<ExcelUser> {

        private IUserService userService;

        public ExcelUserListener(IUserService userService) {
            this.userService = userService;
        }

        // 表示每次读取两千条数据, 就往数据库写一次
        private Integer batch_size = 2000;

        private List<User> userList = new ArrayList<>(batch_size);

        @Override
        public void invoke(ExcelUser data, AnalysisContext context) {
            Date date = new Date();

            User user = new User();
            user.setName(data.getName());
            user.setPassword(DigestUtils.md5Hex(data.getPassword()));
            user.setPhone(data.getPhone());
            user.setRegisterDate(date);
            user.setSex("男".equals(data.getSex()) ? "M" : "F");
            user.setEmail(data.getEmail());
            user.setStatus(data.getStatus());
            user.setBalance(data.getBalance());

            userList.add(user);

            if(userList.size() >= batch_size) {
                userService.batchInset(userList);
                // clear() 清空集合的数据, 释放内存.
                userList.clear();
            }
        }

        // 防止数据不够 2000 条的时候
        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // 因为数据刚刚 2000条
            if(userList.size() > 0) {
                userService.batchInset(userList);
                userList.clear();
            }
        }
}
